package com.zyy.game.tianlong.network;

import com.zyy.game.tianlong.codes.HeartCode;
import com.zyy.game.tianlong.codes.OpCode;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;


/**
 * @author relufi
 * @date 2019/8/10 0010
 */
@Slf4j
public class HeartBeatHandler extends ChannelInboundHandlerAdapter {
    private int heartbeatCount = 0;

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        // IdleStateHandler 所产生的 IdleStateEvent 的处理逻辑.
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent e = (IdleStateEvent) evt;
            if (e.state() == IdleState.READER_IDLE) {
                heartbeatCount++;
                if (heartbeatCount >= 3) {
                    ctx.close();
                } else {
                    ctx.writeAndFlush(new SocketMsg(OpCode.HEART, HeartCode.PING, null));
                }
                return;
            }
        }
        ctx.fireUserEventTriggered(evt);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        SocketMsg socketMsg = ((SocketMsg) msg);
        if (socketMsg.getOpCode() == OpCode.HEART) {
            if (socketMsg.getSubCode() == HeartCode.PONG) {
                heartbeatCount = 0;
            } else if (socketMsg.getSubCode() == HeartCode.PING) {
                ctx.writeAndFlush(new SocketMsg(OpCode.HEART, HeartCode.PONG, null));
            }
        } else {
            ctx.fireChannelRead(msg);
        }
    }
}
